import { db } from '../core/db';

export class settingService {
  private static _instance: settingService;

  static get instance(): settingService {
    if (!this._instance)
      this._instance = new settingService();
    return this._instance;
  }

  private constructor() {
  }

  async init() {
    this._mqttPort = db.instance.query<number>('mqttPort') ?? 1883;
    this._areaCode = db.instance.query<string>('areaCode') ?? 'all';
    this._bluetoothId = db.instance.query<string>('bluetoothId') ?? '';
    this._mqttIp = db.instance.query<string>('mqttIp') ?? '8.138.172.68';
    this._mqttTopic = db.instance.query<string>('mqttTopic') ?? 'sas_topic';
    this._mqttClientId = db.instance.query<string>('mqttClientId') ?? 'sas_client_id';
  }

  hasConfig() {
    return this._mqttIp.length > 0 && this._areaCode.length > 0 && this._mqttTopic.length > 0 && this._mqttClientId.length > 0 && this._mqttPort > 0
      && this._bluetoothId.length > 0;
  }

  private _bluetoothId: string = '';

  get bluetoothId() {
    return this._bluetoothId;
  }

  set bluetoothId(bluetoothId: string) {
    this._bluetoothId = bluetoothId;
    db.instance.updateAwait('bluetoothId', bluetoothId);
  }

  private _areaCode: string = '';

  get areaCode() {
    return this._areaCode;
  }

  set areaCode(areaCode: string) {
    this._areaCode = areaCode;
    db.instance.updateAwait('areaCode', areaCode);
  }

  private _mqttIp: string = '';

  get mqttIp() {
    return this._mqttIp;
  }

  set mqttIp(mqttIp: string) {
    this._mqttIp = mqttIp;
    db.instance.updateAwait('mqttIp', mqttIp);
  }

  private _mqttPort: number = 0;

  get mqttPort() {
    return this._mqttPort;
  }

  set mqttPort(mqttPort: number) {
    this._mqttPort = mqttPort;
    db.instance.updateAwait('mqttPort', mqttPort);
  }

  private _mqttTopic: string = '';

  get mqttTopic() {
    return this._mqttTopic;
  }

  set mqttTopic(mqttTopic: string) {
    this._mqttTopic = mqttTopic;
    db.instance.updateAwait('mqttTopic', mqttTopic);
  }

  private _mqttClientId: string = '';

  get mqttClientId() {
    return this._mqttClientId;
  }

  set mqttClientId(mqttClientId: string) {
    this._mqttClientId = mqttClientId;
    db.instance.updateAwait('mqttClientId', mqttClientId);
  }
}